﻿using DongFangGuoKai.WMSPlatform.Core.Repository;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;

namespace DongFangGuoKai.WMSPlatform.Service.BasicApp.Cell
{
    public partial class CellService : ICellService
    {
        public IRepository<TWarehouse> WarehouseRepo { get; }
        public IRepository<TArea> AreaRepo { get; }
        public IRepository<TShelf> ShelfRepo { get; }
        public IRepository<TCell> CellRepo { get; }
        public IRepository<TDictItem> DictItemRepo { get; }

        public CellService(
            IRepository<TCell> cellRepo,
            IRepository<TArea> areaRepo,
            IRepository<TShelf> shelfRepo,
            IRepository<TWarehouse> warehouseRepo,
            IRepository<TDictItem> dictItemRepo)
        {
            CellRepo = cellRepo;
            AreaRepo = areaRepo;
            ShelfRepo = shelfRepo;
            WarehouseRepo = warehouseRepo;
            DictItemRepo = dictItemRepo;
        }

        /// <summary>
        /// 批量生成仓位
        /// </summary>
        /// <param name="whId">库房ID</param>
        /// <param name="areaId">库区ID</param>
        /// <param name="ShelfIds">货架集合</param>
        /// <param name="MaxLayer">最大层</param>
        /// <param name="indexColumn"></param>
        /// <param name="MaxColumn">最大列</param>
        /// <returns></returns>
        public bool BatchCreateCellAllowErp(out string msg, int whId, int areaId, List<int> ShelfIds, int MaxLayer, int indexColumn, int MaxColumn)
        {
            msg = string.Empty;

            var wareHouse = WarehouseRepo.Get(x => x.Id == whId);
            if (wareHouse == null)
            {
                msg = "库房不存在";
                return false;
            }

            var area = AreaRepo.Get(x => x.Id == areaId);
            if (area == null)
            {
                msg = "库区不存在";
                return false;
            }

            var shelfList = ShelfRepo.GetList(x => x.WhId == whId && x.AreaId == areaId && x.Status == 1 && ShelfIds.Contains(x.Id));
            if (shelfList == null || shelfList.Count == 0)
            {
                msg = "货架不存在";
                return false;

            }
            var logicPart = DictItemRepo.Get(x => x.IsDefault == true && x.TypeCode == "LogicPartType");




            var cellNewModels = new List<TCell>();
            foreach (var shelf in shelfList)
            {


                int lineNO = shelf.Number.GetValueOrDefault();
                if (lineNO <= 0)
                {
                    msg = shelf.Name + "排号不正确";
                    return false;

                }
                //生成每排货架Cell信息  层号*列号*深度
                int maxDepth = shelf.Depth.GetValueOrDefault();
                for (int layerIndex = 1; layerIndex <= MaxLayer; layerIndex++)//层
                {

                    for (int columnIndex = 1; columnIndex <= MaxColumn; columnIndex++)//列
                    {

                        for (int depthIndex = 0; depthIndex < maxDepth; depthIndex++)
                        {
                            bool isMaxDepth = depthIndex == maxDepth - 1;
                            var depthName = depthIndex == 0 ? "" :
                                                 depthIndex == 1 ? "2深位" :
                                                 depthIndex == 2 ? "3深位" :
                                                 depthIndex == 3 ? " 4深位" :
                                                 depthIndex == 4 ? "5深位" : "未知";
                            string name = string.Format("{0}排{1}层{2}列{3}{4}库区", lineNO, layerIndex, columnIndex, depthName, area.Code);
                            string cellCode = string.Format("Cell:{0}_{1}_{2}_{3}_{4}", lineNO.ToString(), layerIndex.ToString(), columnIndex.ToString(), depthIndex.ToString(), area.Code);
                            int erpLineNO = lineNO;
                            string erpCode = GetErpCode(lineNO, layerIndex, columnIndex, shelf.AreaCode);
                            int heightType = (int)EmHeightType.H2300;
                            if (layerIndex == 1 || layerIndex == 2)
                            {
                                heightType = (int)EmHeightType.H2300;
                            }
                            else if (layerIndex == 3)
                            {
                                heightType = (int)EmHeightType.H1600;
                            }
                            else
                            {
                                heightType = (int)EmHeightType.H1150;
                            }
                            TCell cell = new TCell
                            {
                                Code = cellCode,
                                Name = name,
                                WhId = wareHouse.Id,
                                WhName = wareHouse.Name,
                                AreaId = area.Id,
                                AreaName = area.Name,
                                LineNo = lineNO,
                                LayerNo = layerIndex,
                                ColumnNo = columnIndex,
                                DepthIndex = depthIndex,
                                IsLock = false,
                                Status = 1,
                                IsMaxDepth = isMaxDepth,
                                FullStatus = 0,
                                BusinessType = 0,
                                RoutewayId = shelf.RoutewayId,
                                CreateDate = DateTime.Now,
                                ShelfId = shelf.Id,
                                ShelfCode = shelf.Code,
                                ShelfName = shelf.Name,
                                CellType = EmCellType.Normal,
                                Erpcode = erpCode,
                                DistanceValue = Convert.ToDecimal(Math.Sqrt(Math.Pow(layerIndex, 2) + Math.Pow(columnIndex, 2) + Math.Pow(lineNO - 1, 2))),
                                LogicalPartCode = "",
                                LogicalPartName = "",
                                HeightType = heightType,
                                AreaCode = area.Code,
                                WhCode = wareHouse.Code,
                            };
                            cellNewModels.Add(cell);
                        }


                    }


                }

                if (cellNewModels == null || cellNewModels.Count == 0)
                {
                    msg = "没有要生成的仓位";
                    return false;

                }
            }

            //插入仓位，更新货架可用仓位数量，故障仓位数量
            // using var tran = new TransactionScope();  
            var context = CellRepo.GetContext();
            //context.Database.BeginTransaction();
            try
            {

                foreach (var cell in cellNewModels)
                {
                    var isExitsCell = CellRepo.Count(x => x.WhId == cell.WhId && x.AreaId == cell.AreaId && x.ShelfId == cell.ShelfId && x.Code == cell.Code);
                    //if (isExitsCell != 0)
                    //{
                    //    continue;
                    //}
                    CellRepo.Insert(cell);

                }
                foreach (var item in shelfList)
                {
                    var cellCount = CellRepo.Count(x => x.ShelfId == item.Id && x.Status == 1);
                    var disbleCount = CellRepo.Count(x => x.ShelfId == item.Id && x.Status == 0);
                    item.DisabledCellCount = disbleCount;
                    item.CellCount = cellCount;
                    ShelfRepo.Update(item);
                }
                //context.Database.CommitTransaction();
            }
            catch (Exception ex)
            {
                //context.Database.RollbackTransaction();
                msg = "异常：" + ex.Message;
                return false;

            }

            return true;
        }

        public List<TCell> GetCellList(int pageIndex, int pageSize)
        {
            return CellRepo.GetList("Id", pageIndex, pageSize);
        }





        /// <summary>
        /// 生成Erp编码
        /// </summary>
        /// <param name="layerNo">层号</param>
        /// <param name="totalcolumnNO">同一类型货架的总列数</param>
        /// <param name="areaCode">库区编码</param>
        /// <returns></returns>
        private string GetErpCode(int lineNo, int layerNo, int columnNo, string areaCode)
        {
            string startFlag;

            string lineNoStr = lineNo.ToString().PadLeft(2, '0');
            string layerNoStr = layerNo.ToString().PadLeft(3, '0');
            string columnNoStr = columnNo.ToString().PadLeft(3, '0');
            string result;
            switch (areaCode)
            {
                //小料箱    
                case "B01":
                    startFlag = "XX";
                    result = string.Format("{0}{1}{2}{3}", startFlag, lineNoStr, columnNoStr, layerNoStr);
                    break;
                //大料箱
                case "A01":
                    startFlag = "DX";
                    result = string.Format("{0}{1}{2}{3}", startFlag, lineNoStr, columnNoStr, layerNoStr);
                    break;
                //托盘
                case "C01":
                    startFlag = "TP";
                    result = string.Format("{0}{1}{2}", startFlag, columnNoStr, layerNoStr);
                    break;
                //播种墙
                case "D01":
                    startFlag = "FB";
                    result = string.Format("{0}{1}{2}", startFlag, columnNoStr, layerNoStr);
                    break;
                default:
                    startFlag = "";
                    result = "";
                    break;
            }
            return result;





        }


        public bool CreateErpCode(out string msg, int whId, int areaId, List<int> ShelfIds)
        {
            msg = string.Empty;

            var wareHouse = WarehouseRepo.Get(x => x.Id == whId);
            if (wareHouse == null)
            {
                msg = "库房不存在";
                return false;
            }

            var area = AreaRepo.Get(x => x.Id == areaId);
            if (area == null)
            {
                msg = "库区不存在";
                return false;
            }

            var shelfList = ShelfRepo.GetList(x => x.WhId == whId && x.AreaId == areaId && x.Status == 1 && ShelfIds.Contains(x.Id));
            if (shelfList == null || shelfList.Count == 0)
            {
                msg = "货架不存在";
                return false;

            }
            var cellList = CellRepo.GetList(x => x.WhId == whId && x.AreaId == areaId && ShelfIds.Contains(x.ShelfId));
            if (cellList == null || cellList.Count == 0)
            {
                msg = "仓位不在";
                return false;
            }
            string sufflx = "FB";
            foreach (var cellItem in cellList)
            {
                int container=2;
                //if (cellItem.ColumnNo <= 8)
                //{
                //    container = 1;
                //}
                //else
                //{
                //    container = 2;
                //}
                cellItem.Erpcode = string.Format("{0}{1}B{2}50{3}013", sufflx, cellItem.ColumnNo.ToString().PadLeft(4, '0'), container, cellItem.LayerNo);
                CellRepo.Update(cellItem);
            }
            return true;
        }


    }
}
